package com.hccl.config;

import com.mongodb.*;
import com.hccl.mongoEntities.BaseEntity;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.logging.Logger;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;

/**
 * MongoDB providing the database connection.
 */
public class MongoDB {
	private static final Logger LOG = Logger.getLogger(MongoDB.class.getName());
	private static MongoDB INSTANCE;

	private final Datastore datastore;
	public static String DB_NAME = "nxyd";
	public static String DB_ADRESS = "192.168.9.2";
	public static String DB_USER = "";
	public static String DB_PASSWORD = "";
	public static int DB_PORT = 27017;

	public static void setDBConf(String dbName,
								 String dbAddr,
								 String dbUser,
								 String dbPassword,
								 int dbPort) {
		DB_NAME = dbName;
		DB_ADRESS = dbAddr;
		DB_USER = dbUser;
		DB_PASSWORD = dbPassword;
		DB_PORT = dbPort;
	}

	private MongoDB() {
		MongoClientOptions mongoOptions = MongoClientOptions.builder().socketTimeout(120000)
				.connectTimeout(1200000).build(); // SocketTimeout: 60s, ConnectionTimeout: 20min
		MongoCredential credential = MongoCredential.createMongoCRCredential(DB_USER, DB_NAME, DB_PASSWORD.toCharArray());
		MongoClient mongoClient;
		try{
			//mongoClient = new MongoClient(new ServerAddress(DB_ADRESS,DB_PORT), Arrays.asList(credential), mongoOptions);
            /**/if(DB_USER.equals("")){
				mongoClient = new MongoClient(new ServerAddress(DB_ADRESS,DB_PORT),  mongoOptions);

			}else{
				mongoClient = new MongoClient(new ServerAddress(DB_ADRESS,DB_PORT), Arrays.asList(credential), mongoOptions);
			}
			// mongoClient = new MongoClient(new ServerAddress("localhost"), mongoOptions);
		} catch(UnknownHostException e){
			throw new RuntimeException("Error initializing MongoDB", e);
		}

		mongoClient.setWriteConcern(WriteConcern.SAFE);
		datastore = new Morphia()
				.createDatastore(mongoClient, DB_NAME);
		datastore.ensureIndexes();
		LOG.info("Connection to database '" + DB_NAME + "' initialized");
	}

	public static MongoDB instance() {
		if (INSTANCE == null)
			INSTANCE = new MongoDB();
		return INSTANCE;
	}

	// Creating the mongo connection is expensive - (re)use a singleton for performance reasons
	// Both the underlying Java driver and Datastore are thread safe
	public Datastore getDatabase() {
		return datastore;
	}
}
